#处理txt，excel，yaml，json文件
#txt
import json
import os.path
import openpyxl
from openpyxl.workbook import Workbook
from openpyxl.worksheet.worksheet import Worksheet

from common.doLog import DoLog

my_path= r'E:\work\codings\python\2506pro\autoOne\datas'
dl = DoLog()
myLogger = dl.getLogger(__name__)
class DoFile():
    def doTxtRead(self):
        # 文件对象,读文件:  r :反转义
        fileName = r"/myDatas/myFile.txt"

        # f = open(fileName, encoding='utf-8')
        # print(f, type(f))
        # print(f.read())
        # f.close()

        #当代码离开with体之后，自动调用close。即自动关闭文件
        #r+  ：代表以读的形式打开文件，且拥有写的权限
        #w+  :代表以写的形式打开文件，且拥有读的权限，，，，
        #     写的形式：先清空文件，再做其他处理。
        with open(fileName, mode='w+',encoding='utf-8')as f:
            print(f, type(f))
            # print(f.read())
            f.write("12345678")
            print(f.read())
    def doTxtWrite(self,strs):
        fileName = r"/myDatas/myFile1.txt"
        # f = open(fileName, mode='a',encoding='utf-8')
        # #写
        # f.write("abcd")
        # f.close()
        with open(fileName, mode='a',encoding='utf-8') as f:
            f.write(strs)
    def doPNGRead(self):
        # 文件对象,读文件:  r :反转义
        fileName = r"/myDatas/pic.png"

        with open(fileName, mode='r+b')as f:
            print(f, type(f))
            myPNG=f.read()
            return myPNG
    def doPNGWrite(self,fname,strs):
        fileName = os.path.join(my_path,fname)
        print(fileName)
        with open(fileName,mode='w+b')as f:
            f.write(strs)
    #字典转换成json格式的字符串
    def doDictTOJsonStr(self,d):
        s=json.dumps(d)
        print(s,type(s))
        return s
    #json格式的字符串转成字典
    def doJsonTODictStr(self, jsonS):
        d=json.loads(jsonS)
        print(d, type(d))
        return d
    #字典中内容保存成功json格式文件
    def doDictTOJsonFile(self,d,fname):
        fileName = os.path.join(my_path, fname)
        with open(fileName,mode='a',encoding='utf-8')as f:
            json.dump(d,f)
    #json格式文件提取出并转成字典
    def doJsonTODictFile(self,fname):
        fileName = os.path.join(my_path, fname)
        with open(fileName,mode='r',encoding='utf-8')as f:
            d=json.load(f)
            print(d,type(d))
            return d
    #处理excel文件，读，写
    def doExcelRead(self,fname):
        fileName = os.path.join(my_path, fname)

        wk:Workbook=openpyxl.load_workbook(fileName)  #获取工作簿的对象
        st:Worksheet=wk["ac"]  #通过工作簿对象获取sheet对象
        print(st,type(st))

        ss=st.iter_rows(values_only=True)  #获取sheet页中的值
        print(ss)
        print(range(10))
        # for i in ss:
        #     print(i)
        l=[i for i in ss]  #生成列表并返回
        print(f"{l}")
        return l
    #处理excel文件，读，写
    def doExcelReadDIV(self,fname,stname,minRow=None,
                       maxRow=None,minCol=None,maxCol=None):
        fileName = os.path.join(my_path, fname)

        try:
            myLogger.info("开始处理文件了~~~")
            wk:Workbook=openpyxl.load_workbook(fileName)  #获取工作簿的对象
            st:Worksheet=wk[stname]  #通过工作簿对象获取sheet对象
            print(st,type(st))
            #提取部分数据
            ss=st.iter_rows(min_row=minRow,
                            max_row=maxRow,
                            min_col=minCol,
                            max_col=maxCol,
                            values_only=True)  #获取sheet页中的值

        except Exception as e:
            print(f"文件{fileName},sheet名{stname}处理发生了异常，异常信息是：{e}")
            myLogger.exception(f"文件{fileName},sheet名{stname}处理发生了异常，异常信息是：{e}")
        else:
            print(f"处理文件{fileName}，{stname}时未发生异常!")
            myLogger.info(f"处理文件{fileName}，{stname}时未发生异常!")
            l=[i for i in ss]  #生成列表并返回
            print(f"{l}")
            return l
        finally:
            print(f"文件{fileName}处理结束，不知道是否发生异常")
            myLogger.info(f"文件{fileName}处理结束，不知道是否发生异常")

    #写excel文件
    def doExcelWrite(self,fname,stname,ss):
        fileName = os.path.join(my_path, fname)  #新文件名
        wk=openpyxl.Workbook()  #创建新文件
        st:Worksheet=wk.create_sheet(stname,1) #创建sheet对象
        st.cell(1,1,ss) #写一个单元格
        wk.save(fileName)  #保存

if __name__ == '__main__':
    df=DoFile()
    # df.doExcelWrite("mysql2.xlsx","mySheet","hello python")
    # df.doExcelRead("mysql.xlsx")
    df.doExcelReadDIV("jiaYunSuanData.xlsx",'Sheet1',2,maxRow=16,minCol=2)

    # d={"name":"zhansan","age":20}
    # s=df.doDictTOJsonStr(d)
    # df.doDictTOJsonFile(d,"myJson.json")
    # ss='{"name":"zhansan","age":20,"sex":"aa"}'
    # df.doJsonTODictStr(ss)
    # df.doJsonTODictFile("myJson.json")

    # # df.doTxtWrite()
    # sss=df.doPNGRead()   #读取一个文件的内容
    # fileName = "pic4.png"
    # df.doPNGWrite(fileName,sss)  #写一个文件

